/**
 * JAVACC DEMO 1.0
 */
package com.apache.rpc.service.impl.helper;

import com.apache.cache.util.Validator;
import com.apache.database.constant.SystemTools;
import com.apache.database.db.IDao;
import com.apache.rpc.entity.InterfaceRegister;
import com.apache.tools.StrUtil;
import jxl.common.Logger;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * description:  接口注删除缓存策略
 *
 * @author Hou Dayu 创建时间：2016-10-31
 */
//@Service("interfaceRegisterCacheTactics")
public class CacheTactics {

    private IDao interfaceRegisterDao;

    private Logger log = Logger.getLogger(CacheTactics.class);

    private static boolean isOpenTask = false;//是否开启接口监控定时器

    public void setInterfaceRegisterDao(IDao interfaceRegisterDao) {
        this.interfaceRegisterDao = interfaceRegisterDao;
    }

    public void init() {
        String flag = StrUtil.doNull(SystemTools.getInstance().getValue("rpc_initcache"), "1");
        if ("1".equals(flag)) {
            initCaches();
        }
    }

    public void initCaches() {
        try {
            interfaceRegisterDao.initSystemCache();
        } catch (Exception e) {
            log.error("初始化接口缓存失败", e);
        }
    }

    /**
     * description:  添加接口注册缓存
     *
     * @param register
     */
    public void addInterfaceRegisterCache(InterfaceRegister register) {
        List<InterfaceRegister> list = selectInterfaceRegisterCache(register.getBeanId());
        if (Validator.isEmpty(list)) {
            list = new ArrayList<InterfaceRegister>();
        }
        list.add(register);
        SystemTools.getInstance().getCache("")
                .createCacheObject(cacheKey(register.getBeanId()), list);
    }

    /**
     * description: 修改接口注册缓存
     *
     * @param register
     */
    public void editInterfaceRegisterCache(InterfaceRegister register) {
        // delInterfaceRegisterCache(register.getRegisterId(), register.getBeanId());
        List<InterfaceRegister> registers = selectInterfaceRegisterCache(register.getBeanId());
        List<InterfaceRegister> list = new ArrayList();
        if (!Validator.isEmpty(registers)) {
            Iterator<InterfaceRegister> it = registers.iterator();
            String id = register.getRegisterId();
            while (it.hasNext()) {
                InterfaceRegister x = it.next();
                if (!id.equals(x.getRegisterId())) {
                    list.add(x);
                }
            }
        }
        if ("1".equals(register.getFlag())) {
            list.add(register);
        }
        if (!list.isEmpty()) {
            SystemTools.getInstance().getCache("")
                    .createCacheObject(cacheKey(register.getBeanId()), list);
        } else {
            SystemTools.getInstance().getCache("")
                    .removeCacheObject(cacheKey(register.getBeanId()));
        }
    }

    /**
     * description:  删除接口注册缓存
     *
     * @param id
     * @param beanId
     */
    public void delInterfaceRegisterCache(String id, String beanId) {
        List<InterfaceRegister> registers = selectInterfaceRegisterCache(beanId);
        if (Validator.isEmpty(registers))
            return;
        Iterator<InterfaceRegister> it = registers.iterator();
        while (it.hasNext()) {
            InterfaceRegister x = it.next();
            if (id.equals(x.getRegisterId())) {
                it.remove();
                break;
            }
        }
        if (!registers.isEmpty()) {
            SystemTools.getInstance().getCache("").createCacheObject(cacheKey(beanId), registers);
        } else {
            SystemTools.getInstance().getCache("").removeCacheObject(cacheKey(beanId));
        }
    }

    /**
     * description:  按BeanId获取接口注册所有信息
     *
     * @param beanId
     * @return
     */
    @SuppressWarnings("unchecked")
    public List<InterfaceRegister> selectInterfaceRegisterCache(String beanId) {

        List<InterfaceRegister> list = (List<InterfaceRegister>) SystemTools.getInstance()
                .getCache("").getCacheCloneByKey(cacheKey(beanId));
        return list;
    }

    private String cacheKey(String beanId) {
        return "interfaceRegister_" + beanId;
    }

    //运行环境还是开发环境开关(true:运行环境;false开发环境)
    public static boolean isUsagePatterns() {
        String usagePatterns = String.valueOf(
                SystemTools.getInstance().getCache("").getCacheObjectByKey("usage_patterns"));
        return Boolean.parseBoolean(StrUtil.doNull(usagePatterns, "true"));
    }

    //运行环境还是开发环境开关(true:运行环境;false开发环境)
    public static void setUsagePatterns(boolean usagePatterns) {
        SystemTools.getInstance().getCache("")
                .createCacheObject("usage_patterns", String.valueOf(usagePatterns));
    }

    public static boolean isIsOpenTask() {
        return isOpenTask;
    }

    public static void setIsOpenTask(boolean isOpenTask) {
        CacheTactics.isOpenTask = isOpenTask;
    }
}
